# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 同步确认方式：confirm_delivery().py
# @Author: dongguangwen
# @Date  : 2025-04-12 15:31
import pika
from pika.exceptions import UnroutableError

# 建立连接
credentials = pika.PlainCredentials('admin', 'password')
connection = pika.BlockingConnection(
    pika.ConnectionParameters('192.168.1.119', credentials=credentials, virtual_host='my_vhost'))
channel = connection.channel()


# 声明交换器和队列
channel.exchange_declare(exchange='confirm_exchange', exchange_type='direct', durable=True)
channel.queue_declare(queue='confirm_queue', durable=True)
channel.queue_bind(queue='confirm_queue', exchange='confirm_exchange', routing_key='confirm_key')

# ✅ 开启确认模式
channel.confirm_delivery()

try:
    # ✅ 发送消息（注意：无返回值）
    channel.basic_publish(
        exchange='confirm_exchange',
        routing_key='confirm_key',
        body='这是同步确认的消息',
        properties=pika.BasicProperties(delivery_mode=2),
        mandatory=True  # 若没有绑定队列，触发回调
    )
    print("[✔️] 消息已成功发送，并等待 RabbitMQ 确认")
except UnroutableError as e:
    print(f"[❌] 消息不可路由: {e}")
except Exception as e:
    print(f"[‼️] 其他异常: {e}")
finally:
    connection.close()
